package com.example.cloudmusicserve.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @description: UpFileController
 * @author: xiaoyuan
 * @time: 2023/5/27
 */
@RestController
@RequestMapping("/img")
public class UpFileController {

    //文件保存在磁盘的地址
    @Value("${file.save.path}")
    String fileSavePath;

    @RequestMapping("upImgs")
    public String upImgs(HttpServletRequest request,
                         @RequestParam("file") MultipartFile myfile,
                         @RequestParam("desc") String desc) throws IOException {
        File fir=new File(fileSavePath);
        //不存在则创建文件夹
        if(!fir.exists()){
            fir.mkdirs();
        }
        //文件的后缀名
        String suffix=myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf("."));
        //新文件名字 为了防止重复加上UUID
        String newFileName= UUID.randomUUID().toString().replaceAll("-","")+suffix;
//        System.out.println("filesavepath:"+fileSavePath+"   "+"newFileName:"+newFileName);
        //新的文件路径
        File newFile=new File(fileSavePath+newFileName);
        //把文件写入新的File文件
        myfile.transferTo(newFile);
        //url路径=http + :// + server名字 + port端口 + /imges/ + newFileName
        String url=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/images/"+newFileName;
        return url;
    }
}
